/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.market.web.controller;

import com.market.web.EJB.AllItems;
import com.market.web.EJB.TempshoppingcartFacade;
import com.market.web.model.Customer;
import com.market.web.model.Item;
import com.market.web.model.Tempshoppingcart;
import com.market.web.model.TempshoppingcartPK;
import java.io.IOException;
import java.math.BigDecimal;
import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author ps
 */
@WebServlet("/logout")
public class logOutController extends HttpServlet {
     @EJB
    private TempshoppingcartFacade tempShoppingCartFacade;
     
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        
         String userPath = req.getServletPath();

    if (userPath.equals("/logout")) 
       {
           HttpSession session = req.getSession();
           AllItems items  = (AllItems) session.getAttribute("items");
           Customer c = (Customer)session.getAttribute("cust");
           
           if(items == null)
           {
                session.removeAttribute("cust");
                //session.setMaxInactiveInterval(1);
                session.invalidate();
                resp.sendRedirect("homepage.html");
//                RequestDispatcher rd = req.getRequestDispatcher("/homepage.html");
//                rd.forward(req,resp);
//                return;
           }
           else
           {
                for(Item i: items.getItems())
                {
                    TempshoppingcartPK tPK = new TempshoppingcartPK();
                    tPK.setCustID(c.getCustId());
                    tPK.setPid(i.getId());
                    Tempshoppingcart  t = new Tempshoppingcart();
                    t.setItemQty(i.getQty());
                    t.setName(i.getName());
                    BigDecimal b = new BigDecimal(i.getPrice());
                    t.setPrice(b);
                    t.setTempshoppingcartPK(tPK);
                    
                    tempShoppingCartFacade.create(t);
                }
                session.removeAttribute("cust");
                //session.setMaxInactiveInterval(-1);
                session.invalidate();
                resp.sendRedirect("homepage.html");
//                RequestDispatcher rd = req.getRequestDispatcher("/homepage.html");
//                rd.forward(req,resp);

                
           }
        }
    
    }
}
